<template>
  <div class="page-container">
    <el-row class="page-row">
      <el-col :span="24">
        <el-tabs v-model="activeTab">
          <!-- 上行指标设置 -->
          <el-tab-pane label="上行指标设置" name="upstream">
            <el-card class="page-card">
              <template #header>
                <div class="card-header">
                  <span>上行指标配置</span>
                  <el-button type="primary" @click="handleAddUpstream">新增指标</el-button>
                </div>
              </template>
              <div class="scroll-container">
                <el-table :data="upstreamMetrics" style="width: 100%">
                  <el-table-column prop="name" label="指标名称" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column prop="condition" label="条件" />
                  <el-table-column prop="threshold" label="阈值" />
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button size="small" @click="handleEditUpstream(scope.row)">编辑</el-button>
                      <el-button size="small" type="danger" @click="handleDeleteUpstream(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>

          <!-- 下行指标设置 -->
          <el-tab-pane label="下行指标设置" name="downstream">
            <el-card class="page-card">
              <template #header>
                <div class="card-header">
                  <span>下行指标配置</span>
                  <el-button type="primary" @click="handleAddDownstream">新增指标</el-button>
                </div>
              </template>
              <div class="scroll-container">
                <el-table :data="downstreamMetrics" style="width: 100%">
                  <el-table-column prop="name" label="指标名称" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column prop="condition" label="条件" />
                  <el-table-column prop="threshold" label="阈值" />
                  <el-table-column label="操作" width="200">
                    <template #default="scope">
                      <el-button size="small" @click="handleEditDownstream(scope.row)">编辑</el-button>
                      <el-button size="small" type="danger" @click="handleDeleteDownstream(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增指标' : '编辑指标'"
      width="600px"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="指标名称">
          <el-input v-model="form.name" placeholder="请输入指标名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" placeholder="请输入指标描述" />
        </el-form-item>
        <el-form-item label="条件">
          <div class="condition-group">
            <div class="condition-row">
              <span class="condition-category">基础比较：</span>
              <el-radio-group v-model="form.condition" class="condition-options">
                <el-radio label=">">大于</el-radio>
                <el-radio label="<">小于</el-radio>
                <el-radio label="=">等于</el-radio>
                <el-radio label=">=">大于等于</el-radio>
                <el-radio label="<=">小于等于</el-radio>
              </el-radio-group>
            </div>
            <div class="condition-row">
              <span class="condition-category">范围条件：</span>
              <el-radio-group v-model="form.condition" class="condition-options">
                <el-radio label="between">区间内</el-radio>
                <el-radio label="not_between">区间外</el-radio>
              </el-radio-group>
            </div>
            <div class="condition-row">
              <span class="condition-category">特殊条件：</span>
              <el-radio-group v-model="form.condition" class="condition-options">
                <el-radio label="null">无数据</el-radio>
                <el-radio label="not_null">有数据</el-radio>
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item 
          label="阈值" 
          v-if="!['null', 'not_null'].includes(form.condition)"
        >
          <el-input-number 
            v-model="form.threshold" 
            :precision="2"
            :step="0.1"
            style="width: 180px"
          />
          <template v-if="form.condition === 'between' || form.condition === 'not_between'">
            <span class="mx-2">至</span>
            <el-input-number 
              v-model="form.threshold2" 
              :precision="2"
              :step="0.1"
              style="width: 180px"
            />
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const API_BASE_URL = 'http://localhost:8080/api'

interface Metric {
  id?: number
  name: string
  description: string
  condition: string
  threshold: number
  threshold2?: number  // 添加第二个阈值，用于区间条件
  metricType: string
}

const activeTab = ref('downstream')
const upstreamMetrics = ref<Metric[]>([])
const downstreamMetrics = ref<Metric[]>([])
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const form = ref<Metric>({
  name: '',
  description: '',
  condition: '>',
  threshold: 0,
  threshold2: 0,  // 初始化第二个阈值
  metricType: 'DOWNSTREAM'
})

// 获取所有指标
const fetchMetrics = async () => {
  try {
    const [upstreamResponse, downstreamResponse] = await Promise.all([
      axios.get(`${API_BASE_URL}/anomaly-tags/metric-type/UPSTREAM`),
      axios.get(`${API_BASE_URL}/anomaly-tags/metric-type/DOWNSTREAM`)
    ])
    upstreamMetrics.value = upstreamResponse.data
    downstreamMetrics.value = downstreamResponse.data
  } catch (error) {
    ElMessage.error('获取指标列表失败')
  }
}

// 新增上行指标
const handleAddUpstream = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    description: '',
    condition: '>',
    threshold: 0,
    threshold2: 0,
    metricType: 'UPSTREAM'
  }
  dialogVisible.value = true
}

// 新增下行指标
const handleAddDownstream = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    description: '',
    condition: '>',
    threshold: 0,
    threshold2: 0,
    metricType: 'DOWNSTREAM'
  }
  dialogVisible.value = true
}

// 编辑上行指标
const handleEditUpstream = (row: Metric) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 编辑下行指标
const handleEditDownstream = (row: Metric) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除上行指标
const handleDeleteUpstream = async (row: Metric) => {
  try {
    await ElMessageBox.confirm('确定要删除该指标吗？', '提示', {
      type: 'warning'
    })
    await axios.delete(`${API_BASE_URL}/anomaly-tags/${row.id}`)
    ElMessage.success('删除成功')
    fetchMetrics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 删除下行指标
const handleDeleteDownstream = async (row: Metric) => {
  try {
    await ElMessageBox.confirm('确定要删除该指标吗？', '提示', {
      type: 'warning'
    })
    await axios.delete(`${API_BASE_URL}/anomaly-tags/${row.id}`)
    ElMessage.success('删除成功')
    fetchMetrics()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    if (dialogType.value === 'add') {
      await axios.post(`${API_BASE_URL}/anomaly-tags`, form.value)
      ElMessage.success('添加成功')
    } else {
      await axios.put(`${API_BASE_URL}/anomaly-tags/${form.value.id}`, form.value)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchMetrics()
  } catch (error) {
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
  }
}

onMounted(() => {
  fetchMetrics()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}

.condition-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.condition-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.condition-category {
  width: 100px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.condition-options {
  flex: 1;
}

.mx-2 {
  margin: 0 12px;
}

:deep(.el-radio) {
  margin-right: 20px;
  margin-bottom: 8px;
}

:deep(.el-radio__label) {
  font-size: 14px;
}
</style> 